package com.xzit.rcpyxt.config;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xzit.rcpyxt.constant.MessageCode;
import com.xzit.rcpyxt.dto.ResultModel;
import com.xzit.rcpyxt.utils.TOTPUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.InetAddress;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * <p>Title: AuthlerInterceptor</p>
 * <p>Description: 拦截器</p>
 * @author cyy
 * @date 2019/4/19 21:18
 * @version 1.0
 */
public class AuthlerInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LogManager.getLogger(AuthlerInterceptor.class);

    private static final ObjectMapper mapper = new ObjectMapper();

    private static final String CHECKBIND = "/bind/checkUserBind";
    private static final String USERBIND = "/bind/userBind";
    private static final String TEACHERLIST = "/teacher/findTeacherList";
    private static final String STUDENTLIST = "/student/findByStudentList";
    //api文档
    private static final String SWAGGER_RESOURCES = "/swagger-resources";
    private static final String SWAGGER_API_DOC = "/v2/api-docs";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        logger.info("请求 uri："+ uri);
        String token = request.getHeader("token");
        String openId = request.getHeader("openId");
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        if (uri.indexOf("/error") == -1) {
            //获取请求参数
            InputStream is = request.getInputStream();
            StringBuilder responseStrBuilder = new StringBuilder();
            BufferedReader streamReader = new BufferedReader (new InputStreamReader(is, "UTF-8"));
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null)
                responseStrBuilder.append(inputStr);
            String parmeter = responseStrBuilder.toString();
            if (StringUtils.isBlank(parmeter)) {
                parmeter = request.getQueryString();//get请求获取参数 - 除非post/get请求没参数
            }
            logger.info("请 求 头：" + token + ";" + openId + ";" + request.getMethod());
            logger.info("请求参数：" + parmeter);
        }
        String ipAddr = getIpAddr(request);
        logger.info("请 求 ip：" + ipAddr);

        //过滤指定接口
        if (uri.indexOf(CHECKBIND) != -1
                || uri.indexOf(USERBIND) != -1
                || uri.indexOf(TEACHERLIST) != -1
                || uri.indexOf(STUDENTLIST) != -1
                || uri.indexOf(SWAGGER_RESOURCES) != -1
                || uri.indexOf(SWAGGER_API_DOC) != -1) {
            return true;
        }

        //过滤api文档调试
        String loginType = request.getHeader("loginType");
        if (StringUtils.isNotBlank(loginType) && loginType.equals("api")) {
            return true;
        }
        //token校验
        if (StringUtils.isBlank(openId)) {
            printlnResponse(response, new ResultModel(MessageCode.PARAME_NOT_NULL_ERROR.getCode(), "openId不能为空！"));
            return false;
        }
        if (StringUtils.isBlank(token)) {
            printlnResponse(response, new ResultModel(MessageCode.USER_AUTH_ERROR));
            return false;
        }
        String newOpenId = openId + token.substring(token.indexOf("|") + 1, token.length());
        token = token.substring(0, token.indexOf("|"));
        if (!TOTPUtil.verifyTOTPFlexibility(newOpenId, TOTPUtil.SECRET_KEY, token)) {
            printlnResponse(response, new ResultModel(MessageCode.USER_AUTH_ERROR));
            return false;
        }
        long time = System.currentTimeMillis();
        response.setHeader("token", TOTPUtil.generateMyTOTP(openId + time, TOTPUtil.SECRET_KEY) + "|" + time);

        return true;
    }

    private void printlnResponse (HttpServletResponse response, ResultModel resultModel) throws IOException {
        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(resultModel));
        writer.flush();
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
        if (modelAndView != null) {
            logger.info("即将返回到MVC视图：{}", modelAndView.getViewName());
            if (modelAndView.getView() != null) {
                logger.info("返回到MVC视图内容类型ContentType：{}", modelAndView.getView().getContentType());
            }
            if (!modelAndView.getModel().isEmpty()) {
                logger.info("返回到MVC视图{}数据打印如下：", modelAndView.getViewName());
                print(modelAndView.getModel(), "返回数据");
            }
        }
    }

    private void print(Map<String, ?> map, String prefix) {
        if (map != null) {
            Set<String> keys = map.keySet();
            Iterator<String> iter = keys.iterator();
            while (iter.hasNext()) {
                String name = iter.next();
                if (name.contains("org.springframework.validation.BindingResult")) {
                    continue;
                }
                String value = "";
                try {
                    value = mapper.writeValueAsString(map.get(name));
                } catch (JsonProcessingException e) {
                    logger.error("转换参数【{}】发生异常：", name, e);
                }
                logger.info("{} \"{}\"： {}", prefix, name, value);
            }
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

    /**
     * 获取客户端ip
     * @param request
     * @return
     */
    private String getIpAddr (HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("X-Forwarded-For");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("X-Real-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                //可能是代理服务器的ip
                ipAddress = request.getRemoteAddr();
                //本机访问获取ip
                if (ipAddress.equals("127.0.0.1")) {
                    //根据网卡取本机配置的IP
                    InetAddress inet = null;
                    inet = InetAddress.getLocalHost();
                    ipAddress = inet.getHostAddress();
                }
            }
            //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length() // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress="";
        }
        return ipAddress;
    }

}